package.cpath = package.cpath..";./?.dll"

local socket = require "socket"

local aefd = socket.new_poll()

local function client_loop(fd)
    print("prepare to process client "..fd)
    while true do
        local buf = socket.readpacket(fd)
        if buf ~= nil then
            print("recv from client: ",buf)
            print("length="..#buf)
            socket.write(fd,buf.."\n")
        end
    end
end

local function connect_loop(fd)
    print("prepare to process connect: ",fd)
    while true do
        socket.write(fd,"hello server")
        local buf = socket.readpacket(fd)
        if buf ~= nil then
            print("recv from server: ",buf)
            print("length="..#buf)
        end
    end
end

socket.listen(aefd,"0.0.0.0:8730",function(fd,ip,port)
                                      print("accept a connection:"..fd..","..ip..","..port)
                                      socket.start(aefd,fd,client_loop,1,"\n",0) end)

--[[
local fd_tmp = socket.block_connect("127.0.0.1",6379)
print("fd=",fd_tmp)
local function upstream_loop(fd)
    socket.write(fd,"PING\r\n")
    while true do
        local buf = socket.readline(fd,"\r\n")
        print("recv from upstream:",buf)
    end
end
if fd > 0 then
    socket.start(aefd,fd_tmp,upstream_loop,1,"\n",0)
end
]]

socket.connect(aefd,"127.0.0.1:50728",function (fd) 
                                         print("connect success: ",fd)
                                         socket.start(aefd,fd,connect_loop,1,"\n",0) end)


socket.run(aefd)
socket.clear()
